import React, { useEffect, useState } from 'react'
import axios from 'axios';
import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';

export default function HeroDetail() {
  //定义一个 id 值
  // let id = 30;
  //定义一个状态
  let [hero, setHero] = useState({}); //初始值的值, 应该与最后设置的值保持一致
  //1. 获取 params 参数
  // let {id} = useParams();
  //2. 获取 query 参数
  // let [search] = useSearchParams();
  // let id = search.get('id');
  //3. 获取 state 参数
  // let result = useLocation();
  // let id = result.state.id;
  //解构赋值的形式
  let {state: {id}} = useLocation();
  
  //发送请求 获取指定 id 的英雄数据
  useEffect(() => {
    //发送请求
    let getHero = async () => {
      let hero = await axios.get(`http://api.xiaohigh.com/heros/${id}`);
      //更新状态
      setHero(hero.data);
    }
    getHero();
  }, [id]);
  //获取 navigate 函数
  let navigate = useNavigate();

  return (
    <div className='container' style={{paddingTop: 30}}>
      {/* 左侧的结构 */}
      <div className="col-xs-3" style={{background: '#eee', padding: 15}}>
        <button className='btn btn-primary btn-sm' onClick={() => {
          //历史的回退
          navigate(-1);
        }}>返回</button>
        <h3>{hero.name}</h3>
        <p>{hero.type}</p>
        <p><Link to="/hero" state={{id: 1}}>云樱</Link></p>
        <div className="row">
          {
            hero.skills && hero.skills.map(item => {
              return <div key={item.name} className="col-xs-3">
                      <img className='img-circle img-responsive' src={"http://cdn.xiaohigh.com" + item.img} alt="" />
                      <p style={{fontSize:14, textAlign: 'center'}}>{item.name}</p>
                    </div>
            })
          }
        </div>
      </div>

      {/* 右侧结构 */}
      <div className="col-xs-9">
        {/* 大图 */}
        <img className='img-responsive' src={hero.big_image && ("http://cdn.xiaohigh.com" + hero.big_image)} alt="" />
        <hr />
        <p dangerouslySetInnerHTML={{__html: hero.intro}}></p>
      </div>
    </div>
  )
}
